<template>
  <div class="detail-info">
    <el-form :model="ruleForm" label-width="120px" ref="ruleForm" class="demo-ruleForm">
      <div class="detail-info" style="margin-top: 20px">
        <div class="form-item">
          <h4>基本信息</h4>
          <el-form-item label="所属设备：" required >
            <el-select v-model="ruleForm.limit_client" style="width:220px">
              <!--<el-option label="全部" value="0"></el-option>-->
              <el-option label="PC订货" value="10"></el-option>
              <el-option label="惠配通" value="20"></el-option>
              <el-option label="惠付通" value="30"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分公司：">
            <el-input v-model="this.branchName" style="width: 220px" disabled></el-input>
          </el-form-item>
          <el-form-item label="所属部门：">
            <el-input v-model="this.orgName" style="width: 220px" disabled></el-input>
          </el-form-item>
          <el-form-item label="所属仓库：" required>
            <el-select v-model="ruleForm.limit_store_id" filterable clearable>
              <!--<el-option label="全部" value="1"></el-option>-->
              <el-option v-for="item in storeList" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客资类型：" required>
            <el-select v-model="ruleForm.limit_user_type" filterable clearable :loading="customerTypeLoading">
              <el-option v-for="item in this.customerTypeList" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>活动信息</h4>
          <el-form-item label="起止时间：" class="is-required">
            <el-date-picker v-model="activityTime" :editable="false" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" placeholder="活动起止时间" @change="timeChange" style="width: 400px" :picker-options="pickerExpirationDate"
                            :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="促销费用：" required>
            <el-select v-model="ruleForm.promotionfeetype" filterable clearable @change="cuxiaoType">
              <el-option v-for="item in this.salesCostsList" :label="item.promotionName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="限购类型：" class="is-required">
            <el-select v-model="ruleForm.limit_buy_filter" style="width:220px" @change="buyFilterChange">
              <el-option label="不限" value="3"></el-option>
              <el-option label="每单" value="1"></el-option>
              <el-option label="全程" value="2"></el-option>
            </el-select>
            <el-input v-model="ruleForm.limit_buy_count" v-if="buyCountDisabled" style="width: 200px" placeholder="请输入数量"></el-input>
          </el-form-item>
          <el-form-item label="可销售上限：" prop="name">
            <el-input v-model="ruleForm.limit_sell_count" style="width: 200px" placeholder="不输入则表示不限"></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="form-item">
      <el-col :span="2">
        <el-button type="primary" @click="simpleCheck">添加商品</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="lotSet">批量设置</el-button>
      </el-col>
      <el-col :span="6">
        <el-upload class="upload-demo" :action="fileUrl" :on-success="uploadSuccess" :on-remove="removeFlie" :file-list="fileList" accept=".xlsx,.xls">
          <el-button :disabled="primaryDisabled" type="primary">导入表格</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且只能上传一个文件</div>
        </el-upload>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" size="small" style="">
          <a style="text-decoration:none; color:#fff" href="/static/template/商品活动模板.xlsx">下载模板</a>
        </el-button>
      </el-col>
      <el-table :data="tableData" max-height="200" border style="width: 100%; margin-top: 10px">
        <el-table-column prop="productid" label="商品ID" align="center" width="80"></el-table-column>
        <el-table-column prop="name" label="商品名称" align="center" width="120"></el-table-column>
        <el-table-column prop="saleunit" label="单位" align="center" width="80"></el-table-column>
        <el-table-column prop="salenorm" label="规格" align="center" width="90"></el-table-column>
        <el-table-column prop="saleprice" label="系统售价" align="center" width="100"></el-table-column>
        <el-table-column prop="cgprice" label="成本价" align="center" width="90"></el-table-column>
        <el-table-column label="折扣" align="center" width="100">
          <template scope="scope">
            <el-input v-model="scope.row.discount" placeholder="折扣" @change="discountChange($event, scope.$index, '折扣', scope.row)" style="width: 60px"></el-input> %
          </template>
        </el-table-column>
        <el-table-column label="优惠金额" align="center" width="100">
          <template scope="scope">
            <el-input v-model="scope.row.Preferential" placeholder="优惠" @change="discountChange($event, scope.$index, '优惠', scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="promotionprice" label="促销价" align="center" width="100"></el-table-column>
        <el-table-column prop="profit" label="促销毛利" align="center" width="100"></el-table-column>
        <el-table-column prop="promotionalProfit" label="促销毛利率" align="center" width="110"></el-table-column>
        <el-table-column prop="profitLoss" label="毛利损失" align="center" width="100"></el-table-column>
        <el-table-column label="供应商承担金额" align="center" width="120">
          <template scope="scope">
            <el-input v-if="promotionfee_type == ''" v-model="scope.row.providerholdprice" disabled placeholder="未选择促销费用" ></el-input>
            <el-input v-if="promotionfee_type == 1" v-model="scope.row.providerholdprice" disabled placeholder="惠民全担"></el-input>
            <el-input v-if="promotionfee_type == 2" v-model="scope.row.providerholdprice" placeholder="承担金额" @blur="PreferentialChange(scope.row.providerholdprice, scope.$index, '共担')"></el-input>
            <el-input v-if="promotionfee_type == 3" v-model="scope.row.providerholdprice" placeholder="承担金额" @blur="PreferentialChange(scope.row.providerholdprice, scope.$index, '全担')"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="90">
          <template scope="scope">
            <el-button @click="omit(scope.$index, scope.row)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="form-item">
      <el-form label-width="180px">
        <h4>备注</h4>
        <el-input  type="textarea"  placeholder="请输入活动说明" v-model="ruleForm.remark" style="width: 500px"></el-input>
      </el-form>
    </div>
    <div style="margin-left: 40%">
      <el-button type="primary" @click="submit($event)">创 建</el-button>
      <el-button type="primary" @click="submit($event)">保 存</el-button>
      <el-button type="primary" @click="close(menuId, 1)">取 消</el-button>
    </div>
    <!--添加商品弹窗-->
    <el-dialog class="dialog" title="选择商品" :visible.sync="dialogSimple">
      <el-form style="margin-top: 20px; overflow: hidden" :inline="true" :model="formSimple" class="demo-form-inline">
        <el-form-item label="商品分类">
          <el-select v-model="formSimple.type1" style="width: 150px" filterable clearable @change="proList2(formSimple.type1)">
            <el-option v-for="item in productList1" :label="item.cateName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formSimple.type2" style="width: 150px" filterable clearable @change="proList3(formSimple.type2)">
            <el-option v-for="item in productList2" :label="item.cateName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formSimple.type3" style="width: 150px" filterable clearable>
            <el-option v-for="item in productList3" :label="item.cateName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="formSimple.brand" style="width: 150px" filterable clearable>
            <el-option v-for="item in brandList" :label="item.brandName" :value="item.brandId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品ID" placeholder="请输入商品ID">
          <el-input style="width: 100px" v-model="formSimple.ID"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" placeholder="请查询的商品名称">
          <el-input style="width: 120px" v-model="formSimple.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="simpleList">查询</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="lotAdd" style="margin-bottom: 0px;">批量添加</el-button>
      </div>
      <el-table :data="simpleData" v-loading="isLoading" height="600" ref="multipleTable" tooltip-effect="dark" border style="width: 100%" @select-all="handleSelectionChange" @selection-change="handleChange">
        <el-table-column type="selection" :selectable="isCheck" width=""></el-table-column>
        <el-table-column prop="hmpId" label="商品ID" align="center" width=""></el-table-column>
        <el-table-column show-overflow-tooltip prop="hmpName" label="商品名称" align="center" width=""></el-table-column>
        <el-table-column prop="salenorm" label="规格" align="center" width=""></el-table-column>
        <el-table-column prop="saleunit" label="单位" align="center" width=""></el-table-column>
        <el-table-column prop="price" label="系统售价" align="center" width=""></el-table-column>
        <el-table-column prop="proBuyPrice" label="上次入库成本价" align="center" width=""></el-table-column>
        <el-table-column label="操作" align="center" width="">
          <template scope="scope">
            <el-button v-show="scope.row.name === 'add' && scope.row.isActivity.length === 0" @click="add(scope.$index, scope.row, $event)" size="small">添加</el-button>
            <el-button v-show="scope.row.name === 'cancel' && scope.row.isActivity.length === 0" @click="add(scope.$index, scope.row, $event)" size="small">撤销</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="isActivity" label="当前活动" align="center" width="">
          <template scope="scope">
            <span v-for="item in scope.row.isActivity">{{ item }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total"
        @current-change="handleCurrentChange"
        :page-size="Number(pageSize)"
        layout="total, prev, pager, next"
        :total="Number(total)"
        style="padding-top:10px;text-align: right;">
      </el-pagination>
    </el-dialog>
    <!--批量设置-->
    <el-dialog title="批量设置" size="tiny" top="30%" :visible.sync="dialogLotSet">
      <el-form :model="LotForm" :inline="true" label-width="120px" class="demo-form-inline" label-position="left" style="margin: 30px">
        <el-form-item label="折扣">
          <el-input v-model="LotForm.discount"></el-input>
        </el-form-item>
        <el-form-item label="供应商承担金额">
          <el-input v-if="promotionfee_type == ''" v-model="LotForm.providerholdprice" disabled placeholder="未选择促销费用" ></el-input>
          <el-input v-if="promotionfee_type == 1" v-model="LotForm.providerholdprice" disabled placeholder="惠民全担"></el-input>
          <el-input v-if="promotionfee_type != 1 && promotionfee_type != ''" v-model="LotForm.providerholdprice"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="makeLot">确 定</el-button>
      </div>
    </el-dialog>
    </div>
  </div>
</template>
<script>
  import vue from 'vue'
  import { mapState } from 'vuex'
  import { apiHost, apiURL } from '../../../../config/settings.js'
  import mixins from '../../../../components/mixins.vue'
  import { activity, getInfo } from '../../../../config/proxy.js'
  export default {
    mixins: [mixins],
    data () {
      return {
        pickerExpirationDate: { // 截止日期类型禁用时间段
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        ruleForm: {
          limit_branch_id: '',
          limit_department: '',
          newBranchId: '',
          limit_client: '',    // 设备
          limit_store_id: '',  // 仓库
          limit_user_type: '', // 客资
          start_time: '',
          end_time: '',
          promotionfeetype: '', // 促销费用
          limit_buy_filter: '', // 限购类型
          limit_buy_count: '',  // 数量
          limit_sell_count: '', // 销售上限
          remark: ''
        },
        customerTypeList: [],  // 客资类型
        salesCostsList: [],    // 促销费用列表
        promotionfee_type: '', // 费用类型
        activityTime: '',      // 时间
        tableData: [],         // 商品信息
        productList: [],       // 提交的商品数据
        all: [],    // 选中项集合
        menuId: '', // 页签Id
        uid: '',    // row
        // 选择单品弹窗
        dialogSimple: false,
        brandList: [],
        productList1: [],
        productList2: [],
        productList3: [],
        formSimple: {
          type1: '',
          type2: '',
          type3: '',
          brand: '',
          ID: '',
          name: ''
        },
        // 选择单品表格
        isLoading: false,
        simpleData: [],
        total: '',
        page: 1,
        pageSize: 10,
        // 导入EXCEL
        fileList: [],
        fileUrl: '',
        buyCountDisabled: false,
        primaryDisabled: false,
        dialogLotSet: false,
        LotForm: {
          providerholdprice: '',
          discount: ''
        },
        id: '',
        promotion_id: '',
        promotionproduct_id: '',
        saleunit_convert: '',
        cgunit_convert: ''
      }
    },
    methods: {
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      },
      close (id, num) {
        if (num) {
          this.$confirm('确定要取消创建单品折扣吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },       // 取消
      searchCustomerType () {
        var _data = ''
        this.customerTypeLoading = true
        getInfo.client(_data, (res) => {
          if (res.message === 'ok') {
            this.customerTypeLoading = false
            this.customerTypeList = res.content.content
          }
        })
      }, // 客资类型
      timeChange (val) {
        if (val) {
          this.ruleForm.start_time = val[0]
          this.ruleForm.end_time = val[1]
          this.ruleForm.promotionfeetype = ''
          this.searchSalesCosts()
        } else {
          this.ruleForm.start_time = ''
          this.ruleForm.end_time = ''
        }
      },      // 时间变化
      searchSalesCosts () {
        var _data = {
          branchId: this.branchId,
          activityType: 1,
          startTime: this.ruleForm.start_time,
          endTime: this.ruleForm.end_time
        }
        activity.cxfy.allList(_data, (res) => {
          if (res.message === 'ok') {
            this.salesCostsList = res.content
          } else {
            this.message('促销费用获取失败', 'error')
          }
        })
      },   // 促销费用
      cuxiaoType (val) {
        console.log(val)
        for (let i in this.tableData) {
          this.tableData[i].providerholdprice = ''
        }
        if (!val) {
          this.promotionfee_type = ''
        } else {
          for (const i in this.salesCostsList) {
            if (this.salesCostsList[i].id === val) {
              this.promotionfee_type = this.salesCostsList[i].promotionType
            }
          }
        }
      },      // 促销费用变化
      buyFilterChange (val) {
        this.ruleForm.limit_buy_count = ''
        val === '3' ? this.buyCountDisabled = false : this.buyCountDisabled = true
      }, // 限购类型变化
      proList1 () {
        getInfo.getCate({pid: 0}, (res) => {
          if (res.message === 'ok') {
            this.productList1 = res.content
          }
        })
      },           // 一级分类
      proList2 (val) {
        this.productList2 = []
        this.formSimple.type2 = ''
        getInfo.getCate({pid: val}, (res) => {
          if (res.message === 'ok') {
            this.productList2 = res.content
          }
        })
      },        // 二级分类
      proList3 (val) {
        this.productList3 = []
        this.formSimple.type3 = ''
        this.formSimple.brand = ''
        getInfo.getCate({pid: val}, (res) => {
          if (res.message === 'ok') {
            this.productList3 = res.content
          }
        })
        getInfo.getBrand({cateId: val}, (res) => {
          if (res.message === 'ok') {
            this.brandList = res.content
          }
        })
      },        // 三级分类
      omit (index, row) {
        this.$confirm('确定要删除该条商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.splice(index, 1)
        }).catch(() => {
        })
      },     // 删除商品
      simpleCheck () {
        if (!this.ruleForm.limit_user_type) {
          this.$message({
            showClose: true,
            message: '请选择客资类型后再添加商品',
            type: 'error'
          })
        } else if (!this.ruleForm.start_time) {
          this.$message({
            showClose: true,
            message: '请选择活动开始时间再添加商品',
            type: 'error'
          })
        } else {
          this.dialogSimple = true
          // 重置
          this.formSimple.ID = ''
          this.formSimple.name = ''
          this.formSimple.type1 = ''
          this.formSimple.type2 = ''
          this.formSimple.type3 = ''
          this.formSimple.brand = ''
          this.simpleData = []
          this.page = 1
          this.total = ''
//          if (this.tableData.length !== 0) {
//            for (let j = 0; j < this.simpleData.length; j++) {
//              let flag = true
//              for (let i = 0; i < this.tableData.length; i++) {
//                console.log(this.tableData[i].hmpId === this.simpleData[j].hmpId)
//                if (this.tableData[i].hmpId === this.simpleData[j].hmpId) {
//                  this.simpleData[j].name = 'cancel'
//                  flag = false
//                } else {
//                  this.simpleData[j].name = 'add'
//                }
//                if (!flag) {
//                  i = this.tableData.length
//                }
//              }
//            }
//          } else {
//            for (let i = 0; i < this.simpleData.length; i++) {
//              this.simpleData[i].name = 'add'
//            }
//          }
        }
      },        // 添加商品按钮
      simpleList () {
        this.selectGoods()
      },
      selectGoods () {
        this.simpleData = []
        this.isLoading = true
        const queryData = {
          branchId: this.branchId,
          userType: this.ruleForm.limit_user_type,
          promotionType: 7,
          startTime: this.ruleForm.start_time,
          endTime: this.ruleForm.end_time,
          fourCate: this.formSimple.brand,
          page: this.page,
          pageSize: this.pageSize,
          hmpId: this.formSimple.ID,
          hmpName: this.formSimple.name,
          firstCate: this.formSimple.type1,
          secondCate: this.formSimple.type2,
          thirdCate: this.formSimple.type3,
          isMaster: 1,
          flag: 1,
//          classId: '',
          showType: [1, 3, 4]
        }
        console.log(queryData, '查商品提交数据')
        getInfo.searchProduct(queryData, (res) => {
          console.log(res, '商品分页数据')
          if (res.message === 'ok' && res.content.content !== null) {
            if (this.tableData.length !== 0) {
              for (var i = 0; i < res.content.content.length; i++) {
                let a = true
                for (var j = 0; j < this.tableData.length; j++) {
                  if (res.content.content[i].hmpId === this.tableData[j].productid) {
                    res.content.content[i].name = 'cancel'
                    a = false
                  } else {
                    res.content.content[i].name = 'add'
                  }
                  if (a === false) {
                    j = this.tableData.length
                  }
                }
              }
            } else {
              res.content.content.forEach(function (item, index) {
                item.name = 'add'
              })
            }
            this.isLoading = false
            this.simpleData = res.content.content
            this.total = res.content.count
          } else if (res.message === 'ok' && res.content.content === null) {
            this.total = ''
            this.isLoading = false
          } else {
            this.$message({
              showClose: true,
              message: '查询单品失败',
              type: 'error'
            })
            this.total = ''
            this.isLoading = false
          }
        })
      },             // 查询商品列表
      handleCurrentChange (val) {
        this.page = val
        this.selectGoods()
      },  // 分页
      add (index, row, event) {
        if (event.target.innerText === '添加') {
          row.name = 'cancel'
          this.$refs.multipleTable.toggleRowSelection(row, true)
          const arr = {
            productid: row.hmpId,   // 商品ID
            name: row.hmpName,      // 商品名称
            saleunit: row.saleunit, // 销售单位
            salenorm: row.salenorm, // 销售规格
            saleprice: row.price,   // 系统售价
            saleunit_convert: row.saleUnitConvert, // 销售单位和最小单位转换值
            cgunit_convert: row.CGUnitConvert,     // 采购单位和最小单位转换值
            cgprice: row.proBuyPrice,              // 最近一次采购价
            promotionproduct_id: '',               // 新添加商品
            discount: '',
            Preferential: '',
            promotionprice: '',
            profit: '',
            promotionalProfit: '',
            profitLoss: '',
            providerholdprice: ''
          }
          this.tableData.unshift(arr)
        } else {
          row.name = 'add'
          this.$refs.multipleTable.toggleRowSelection(row, false)
          const index = this.tableData.indexOf(row)
          this.tableData.splice(index, 1)
        }
      },    // 单个添加
      lotAdd () {
        // 状态变为撤销
        for (let i in this.simpleData) {
          let flag = true
          for (let j = 0; j < this.all.length; j++) {
            if (this.simpleData[i].hmpId === this.all[j].hmpId) {
              this.simpleData[i].name = 'cancel'
              flag = false
            } else {
              this.simpleData[i].name = 'add'
            }
            if (!flag) {
              j = this.all.length
            }
          }
        }
        // 添加进去
        this.all.forEach((item, index) => {
          if (this.tableData.indexOf(item) === -1) {
            const arr = {
              productid: item.hmpId,   // 商品ID
              name: item.hmpName,      // 商品名称
              saleunit: item.saleunit, // 销售单位
              salenorm: item.salenorm, // 销售规格
              saleprice: item.price,   // 系统售价
              saleunit_convert: item.saleUnitConvert, // 销售单位和最小单位转换值
              cgunit_convert: item.CGUnitConvert,     // 采购单位和最小单位转换值
              cgprice: item.proBuyPrice,              // 最近一次采购价
              promotionproduct_id: '',                 // 新添加商品
              discount: '',
              Preferential: '',
              promotionprice: '',
              profit: '',
              promotionalProfit: '',
              profitLoss: '',
              providerholdprice: ''
            }
            this.tableData.unshift(arr)
          }
        })
      },                  // 批量添加
      handleChange (all) {
        this.all = all
      },           // 全选
      handleSelectionChange (all) {
        this.all = all
      },  // 全选
      isCheck (row, index) {
        return row.isActivity.length === 0 && row.name === 'add'
      },         // 是否可选
      discountChange (e, i, v, s) {
        let price = this.tableData[i].saleprice      // 系统售价
        let proBuyPrice = this.tableData[i].cgprice  // 上次入库成本价
        console.log(proBuyPrice)
        if (v === '折扣') {
          if (e % 1 !== 0 || e > 100) {
            this.$message({
              showClose: true,
              message: '请填写正确的折扣！',
              type: 'error'
            })
            this.tableData[i].discount = '' // 折扣
          } else if (e === '') {
            this.tableData[i].promotionprice = '' // 促销价
            this.tableData[i].profit = ''         // 促销毛利
            this.tableData[i].promotionalProfit = ''  // 促销毛利率
            this.tableData[i].profitLoss = ''         // 毛利损失
            this.tableData[i].Preferential = ''       // 优惠金额
            vue.set(this.tableData, i, s)
          } else {
            console.log('折扣')
            // 促销价 = 系统售价 * 折扣价 或 系统售价 - 优惠金额
            // 毛利损失 = 系统售价 - 促销价
            // 毛利率 = （促销价 - 成本价）/ 成本价
            // 毛利 = 促销价 - 成本价
            // 毛利 < 供应商承担金额
            this.tableData[i].promotionprice = (Number(price) * Number(e / 100)).toFixed(2) // 促销价
            this.tableData[i].profit = (Number(this.tableData[i].promotionprice) - Number(proBuyPrice)).toFixed(2) // 促销毛利
            this.tableData[i].promotionalProfit = ((this.tableData[i].promotionprice - proBuyPrice) / proBuyPrice * 100).toFixed(2) + '%' // 毛利率
            this.tableData[i].profitLoss = (price - this.tableData[i].promotionprice).toFixed(2) // 毛损
            this.profit_loss = this.tableData[i].profitLoss
            this.tableData[i].Preferential = (price - this.tableData[i].promotionprice).toFixed(2) // 优惠金额
            vue.set(this.tableData, i, s)
          }
        } else {
          if (e % 1 !== 0 || e > this.tableData[i].saleprice) {
            this.$message({
              showClose: true,
              message: '请填写正确的优惠金额!',
              type: 'error'
            })
            this.tableData[i].Preferential = ''
          } else if (e === '') {
            this.tableData[i].promotionprice = ''
            this.tableData[i].profit = ''
            this.tableData[i].promotionalProfit = ''
            this.tableData[i].profitLoss = ''
            this.tableData[i].discount = ''
            vue.set(this.tableData, i, s)
          } else {
            console.log('优惠')
            this.tableData[i].promotionprice = (Number(price - e)).toFixed(2) // 促销价
            this.tableData[i].profit = (Number(this.tableData[i].promotionprice) - Number(proBuyPrice)).toFixed(2) // 促销毛利
            this.tableData[i].promotionalProfit = ((this.tableData[i].promotionprice - proBuyPrice) / proBuyPrice * 100).toFixed(2) + '%' // 毛利率
            this.tableData[i].profitLoss = (price - this.tableData[i].promotionprice).toFixed(2) // 毛损
            this.profit_loss = this.tableData[i].profitLoss
            this.tableData[i].discount = parseInt(this.tableData[i].promotionprice / this.tableData[i].saleprice * 100) // 折扣
            vue.set(this.tableData, i, s)
          }
        }
      },  // 修改折扣
      PreferentialChange (e, i, v) {
        if (!this.tableData[i].discount || !this.tableData[i].Preferential) {
          this.$message({
            showClose: true,
            message: '请填写折扣或优惠金额',
            type: 'error'
          })
          this.tableData[i].providerholdprice = ''
        } else {
          if (v === '全担') {
            if (Number(e) <= Number(this.tableData[i].profitLoss)) {
              this.$message({
                showClose: true,
                message: '供应商承担金额必须大于毛利损失金额',
                type: 'error'
              })
              this.tableData[i].providerholdprice = ''
            }
          } else {
            if (Number(e) < 0) {
              this.$message({
                showClose: true,
                message: '共担金额不能为负',
                type: 'error'
              })
              this.tableData[i].providerholdprice = ''
            }
          }
        }
      }, // 供应商承担金额验证
      lotSet () {
        if (this.tableData.length > 0) {
          this.dialogLotSet = true
          this.LotForm.discount = ''
          this.LotForm.providerholdprice = ''
        } else {
          this.$message({
            showClose: true,
            message: '暂无可设置商品',
            type: 'warning'
          })
        }
      },  // 批量设置按钮
      makeLot () {
        this.dialogLotSet = false
        for (let i in this.tableData) {
          this.discountChange(this.LotForm.discount, i, '折扣', this.tableData[i])
          this.tableData[i].discount = this.LotForm.discount
          this.tableData[i].providerholdprice = this.LotForm.providerholdprice
        }
      }, // 批量设置
      uploadSuccess (res, file, fileList) {
        console.log(res)
        if (res.message === 'ok') {
          this.tableData = res.content
          this.primaryDisabled = true
        } else {
          this.primaryDisabled = false
          this.fileList = []
          this.$message({
            showClose: true,
            message: '上传失败',
            type: 'error'
          })
        }
      }, // 导入文件
      removeFlie (file, fileList) {
        if (fileList.length === 0) {
          this.primaryDisabled = false
          this.tableData = []
        }
      },         // 删除文件
      submit (event) { // 提交
        const start = new Date(this.ruleForm.start_time).getTime()
        const now = new Date().getTime()
        if ((this.ruleForm.limit_buy_filter === '2' || this.ruleForm.limit_buy_filter === '1') && !this.ruleForm.limit_buy_count) {
          this.$message({
            showClose: true,
            message: '请输入限购数量',
            type: 'error'
          })
          return false
        }
        if (start <= now) {
          this.$message({
            showClose: true,
            message: '开始时间必须晚于当前时间',
            type: 'error'
          })
          return false
        }
        if (!this.ruleForm.limit_client || !this.ruleForm.start_time || !this.ruleForm.limit_store_id || !this.ruleForm.limit_user_type || !this.ruleForm.promotionfeetype || !this.ruleForm.limit_buy_filter) {
          this.$message({
            showClose: true,
            message: '请将必填项填写完整',
            type: 'error'
          })
          return false
        }
        for (let i in this.tableData) {
          if ((!this.tableData[i].discount || !this.tableData[i].Preferential) || ((!this.promotionfee_type || this.promotionfee_type === '1') && !this.tableData[i].providerholdprice)) {
            this.$message({
              showClose: true,
              message: '请将商品信息填写完整',
              type: 'error'
            })
            return false
          }
        }
        for (let i in this.tableData) {
          if (this.promotionfee_type === 2) {
            if (this.tableData[i].providerholdprice < 0) {
              this.$message({
                showClose: true,
                message: '供应商承担金额不能为负',
                type: 'error'
              })
              return false
            }
          }
          if (this.promotionfee_type === 3) {
            if (this.tableData[i].providerholdprice <= this.tableData[i].profitLoss) {
              this.$message({
                showClose: true,
                message: '供应商承担金额不能小于毛利损失',
                type: 'error'
              })
              return false
            }
          }
        }
        let g = []
        if (this.tableData.length === 0) {
          this.$message({
            showClose: true,
            message: '商品信息至少为一条',
            type: 'error'
          })
          return false
        } else {
          for (let i in this.tableData) {
            var productInfo = {}
            g.push(this.tableData[i].promotionalProfit.replace('%', '')) // 促销毛利率
            productInfo.productid = this.tableData[i].productid
            productInfo.name = this.tableData[i].name
            productInfo.saleunit = this.tableData[i].saleunit
            productInfo.salenorm = this.tableData[i].salenorm
            productInfo.saleprice = (this.tableData[i].saleprice * 100).toFixed(0)
            productInfo.cgprice = (this.tableData[i].cgprice * 100).toFixed(0) // 上次入库成本价
            productInfo.discount = this.tableData[i].discount                  // 折扣
            productInfo.Preferential = (this.tableData[i].Preferential * 100).toFixed(0)     // 优惠金额
            productInfo.promotionprice = (this.tableData[i].promotionprice * 100).toFixed(0) // 促销价
            productInfo.providerholdprice = this.tableData[i].providerholdprice ? (this.tableData[i].providerholdprice * 100).toFixed(0) : 0 // 供应商承担金额
            productInfo.cgunit_convert = this.tableData[i].cgunit_convert
            productInfo.saleunit_convert = this.tableData[i].saleunit_convert
            this.productList.push(productInfo)
          }
        }
        let Data = {
          limit_branch_id: this.branchId === 1 ? this.ruleForm.limit_branch_id : this.branchId,
          end_time: this.ruleForm.end_time,
          start_time: this.ruleForm.start_time,
          grossProfitRate: g,
          iscaogao: event.target.innerText === '创 建' ? 2 : 1,
          uorId: this.uorId,
          gwId: this.roleId,
          limit_buy_filter: this.ruleForm.limit_buy_filter,
          limit_buy_count: this.ruleForm.limit_buy_count,
          limit_client: this.ruleForm.limit_client,
          limit_department: this.orgId,
          limit_store_id: this.ruleForm.limit_store_id,
          remark: this.ruleForm.remark,
          limit_sell_count: this.ruleForm.limit_sell_count,
          limit_user_type: this.ruleForm.limit_user_type,
          newBranchId: this.bid,
          promotionfeetype: this.ruleForm.promotionfeetype,
          userId: this.userId,
          userName: this.userName,
          product: this.productList
        }
        if (this.uid) {
          Data.id = this.uid.id
          Data.promotion_id = this.uid.promotion_id
          console.log('编辑提交的数据', Data)
          activity.sphd.dpzk.update(Data, (res) => {
            console.log(res)
            if (res.code === 0) {
              this.$message({
                showClose: true,
                message: '单品折扣修改成功！',
                type: 'success'
              })
              this.$store.dispatch('dpzkState', this.$store.state.updateState.dpzkState + 1)
              this.close(this.menuId)
            } else if (res.code === 400) {
              this.$message({
                showClose: true,
                message: res.message,
                type: 'error'
              })
              Data = {}
              this.productList = []
            } else {
              this.$message({
                showClose: true,
                message: '请求服务器失败',
                type: 'error'
              })
              Data = {}
              this.productList = []
            }
          })
        } else {
          console.log('创建提交的数据', Data)
          activity.sphd.dpzk.create(Data, (res) => {
            console.log(res)
            if (res.code === 0) {
              this.$message({
                showClose: true,
                message: '创建单品折扣成功！',
                type: 'success'
              })
              this.$store.dispatch('dpzkState', this.$store.state.updateState.dpzkState + 1)
              this.close('dpzk_add')
            } else if (res.code === 400) {
              this.$message({
                showClose: true,
                message: res.message,
                type: 'error'
              })
              Data = {}
              this.productList = []
            } else {
              this.$message({
                showClose: true,
                message: '请求服务器失败',
                type: 'error'
              })
              Data = {}
              this.productList = []
            }
          })
        }
      },  // 提交
      edit (id) {
        activity.sphd.detail({id: id}, (res) => {
          console.log(res, '编辑的详情')
          if (res.message === 'ok') {
            this.id = res.content.id
            this.promotion_id = res.content.promotion_id
            this.promotionproduct_id = res.content.main_product[0].promotionproduct_id
            this.saleunit_convert = res.content.main_product[0].saleunit_convert
            this.cgunit_convert = res.content.main_product[0].cgunit_convert
            this.ruleForm.limit_client = res.content.limit_client
            this.ruleForm.branchName = res.content.branchName
            this.ruleForm.orgName = res.content.departName
            this.ruleForm.limit_store_id = res.content.limit_store_id
            this.ruleForm.limit_user_type = Number(res.content.limit_user_type)
            this.activityTime = [res.content.start_time, res.content.end_time]
            this.ruleForm.promotionfeetype = res.content.main_product[0].promotionfeetype
            this.ruleForm.limit_buy_filter = res.content.limit_buy_filter
            this.ruleForm.limit_buy_count = res.content.limit_buy_count
            this.ruleForm.limit_sell_count = res.content.limit_sell_count
            const resProduct = res.content.main_product
            const resItem = {}
            console.log(resProduct)
            resProduct.forEach((item, i) => {
              resItem.productid = item.product_id
              resItem.name = item.name
              resItem.saleunit = item.saleunit
              resItem.salenorm = item.salenorm
              resItem.saleprice = item.saleprice / 100
              resItem.cgprice = item.cgprice / 100
              resItem.discount = item.discount
              resItem.Preferential = item.cxmls
              resItem.promotionprice = item.price_real
              resItem.profit = item.cxml / 100
              resItem.promotionalProfit = item.cxmll + '%'
              resItem.profitLoss = item.cxmls
              resItem.providerholdprice = item.providerholdprice === 0 ? item.providerholdprice : item.providerholdprice / 100
              this.tableData.unshift(resItem)
            })
          } else {
            this.$message({
              showClose: true,
              message: '请求服务器失败',
              type: 'error'
            })
          }
        })
      }        // 编辑
    },
    computed: mapState({
      userName: function (state) {
        return state.user.info.user_name
      },
      userId: function (state) {
        return state.user.info.user_id
      },
      uorId: function (state) {
        return state.user.info.uor_id
      },
      orgName: function (state) {
        return state.user.info.parOrgName
      },
      orgId: function (state) {
        return state.user.info.or_org_id
      },
      roleId: function (state) {
        return Number(state.user.info.roleid)
      },
      branchName: function (state) {
        return state.user.info.branchId === 1 ? '总公司' : state.user.info.branchName
      },
      branchId: function (state) {
        return state.user.info.branchId
      },
      bid: function (state) {
        return state.user.info.branchOrgId
      }
    }),
    created () {
      this.proList1()             // 一级分类
      this.searchCustomerType()   // 客资列表
      this.fileUrl = 'http://' + apiHost.newCms + ':20000' + apiURL.ppq_upload
//      this.ruleForm.limit_branch_id = this.branchId
//      this.ruleForm.newBranchId = this.bid
//      this.ruleForm.limit_department = this.orgId
//      this.ruleForm.uorId = this.uorId
      this.menuId = this.$store.state.tab.menuId  // 页签Id
      this.uid = this.$store.state.tab.uid        // row
      if (this.uid) {
        console.log('编辑')
        this.edit(this.uid.id)
      } else {
        console.log('新增')
      }
    }
  }
</script>
<style>
  .dialog .el-form--inline div {
    display: inline-block;
    float: left;
  }
  .stair {
    margin-left: 66px;
    font-size: 14px;
    color: #48576a;
  }
</style>
